package com.zenith.storage.controller;

import com.zenith.common.annotation.request.SecurePostMapping;
import com.zenith.common.result.Result;
import com.zenith.storage.po.dto.ChunkCompleteDTO;
import com.zenith.storage.po.dto.ChunkInitDTO;
import com.zenith.storage.po.dto.ChunkUploadDTO;
import com.zenith.storage.service.ChunkUploadService;
import com.zenith.storage.po.vo.ChunkInitVO;
import com.zenith.storage.po.vo.ChunkStatusVO;
import com.zenith.storage.po.vo.ChunkUploadVO;
import com.zenith.storage.po.vo.FileVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import jakarta.validation.Valid;

/**
 * 分片上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/storage/chunk")
@RequiredArgsConstructor
public class ChunkUploadController {
    
    private final ChunkUploadService chunkUploadService;
    
    /**
     * 初始化分片上传
     */
    @SecurePostMapping("/initChunkUpload")
    public Result<ChunkInitVO> initChunkUpload(@Valid @RequestBody ChunkInitDTO chunkInitDTO) {
        try {
            ChunkInitVO result = chunkUploadService.initChunkUpload(chunkInitDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("初始化分片上传失败", e);
            return Result.fail("初始化分片上传失败");
        }
    }
    
    /**
     * 上传分片
     */
    @SecurePostMapping("/chunkUploadService")
    public Result<ChunkUploadVO> uploadChunk(@Valid @RequestBody ChunkUploadDTO chunkUploadDTO) {
        try {
            ChunkUploadVO result = chunkUploadService.uploadChunk(chunkUploadDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("上传分片失败", e);
            return Result.fail("上传分片失败");
        }
    }
    
    /**
     * 完成分片上传
     */
    @SecurePostMapping("/completeChunkUpload")
    public Result<FileVO> completeChunkUpload(@Valid @RequestBody ChunkCompleteDTO chunkCompleteDTO) {
        try {
            FileVO result = chunkUploadService.completeChunkUpload(chunkCompleteDTO);
            return Result.success(result);
        } catch (Exception e) {
            log.error("完成分片上传失败", e);
            return Result.fail("完成分片上传失败");
        }
    }
    
    /**
     * 获取分片上传状态
     */
    @SecurePostMapping("/getChunkStatus/{uploadKey}")
    public Result<ChunkStatusVO> getChunkStatus(@PathVariable String uploadKey) {
        try {
            ChunkStatusVO result = chunkUploadService.getChunkStatus(uploadKey);
            return Result.success(result);
        } catch (Exception e) {
            log.error("获取分片上传状态失败", e);
            return Result.fail("获取分片上传状态失败");
        }
    }
}